package com.zhz.lib.cms.manage.custom;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.hibernate.Hibernate;
import org.hibernate.classic.Session;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;

import com.zhz.lib.cms.domain.custom.Custom;
import com.zhz.lib.cms.manage.BaseActionWithApprove;
import com.zhz.lib.cms.utils.zhz.ZhzSecurityUtil;
import com.zhz.project.common.util.alibaba.StringUtil;
import com.zhz.project.common.util.hibernate.BaseDAO;
import com.zhz.project.common.util.zhzutil.ZhzDateUtil;
import com.zhz.project.common.util.zhzutil.ZhzHttpRequestUtil;
import com.zhz.project.common.util.zhzutil.ZhzStringUtil;

/**
 * 定制模块的处理类
 * 
 * @author liwei2672
 * @version $Id: customAction.java, v 0.1 2010-7-14 下午09:17:08 liwei2672 Exp $
 */
public class customAction extends BaseActionWithApprove {

    private static final int           length = 30;
    private static String              TABLE  = "Custom";
    private static String              KEY    = "customId";
    private static String              LIST   = "customlist";
    private static String              LINK   = "LINK";
    private static String              CUSTOM = "CUSTOM";

    private static Map<String, String> map;

    static {
        map = new java.util.HashMap<String, String>();
        map.put("HIDE", "隐藏模块");
    }

    private static Logger              logger = Logger.getLogger(customAction.class);

    // 事务模板
    private TransactionTemplate        transactionTemplate;

    /**
     * 不给参数，默认执行此处
     */
    public ActionForward unspecified(ActionMapping mapping, ActionForm form,
                                     HttpServletRequest request, HttpServletResponse response)
                                                                                              throws Exception {
        // 默认显示定制模块列表
        return customlist(mapping, form, request, response);
    }

    /**
     * 显示定制模块列表
     * 
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    public ActionForward customlist(ActionMapping mapping, ActionForm form,
                                    HttpServletRequest request, HttpServletResponse response)
                                                                                             throws Exception {
        // ////////////////////////////////////////////////////////////////////////

        // 获取选择的定制模块选项
        String radiooption = ZhzHttpRequestUtil.getParameters(request, "radiooption");

        // 获取“一级模块列表”
        String leveloneselected = ZhzHttpRequestUtil.getParameters(request, "leveloneselected");

        request.setAttribute("radiooption", radiooption);
        request.setAttribute("leveloneselected", leveloneselected);

        // 上面是提取参数并输出到页面中
        // ////////////////////////////////////////////////////////////////////////

        String whereStatement = BaseDAO.WHERE;
        StringBuffer fanyeHref = new StringBuffer();
        fanyeHref.append("customManage.do?method=customlist");

        if (StringUtil.equals(radiooption, "levelone")) {
            whereStatement += " and  level='1'";
        } else if (StringUtil.equals(radiooption, "leveltwo")) {
            whereStatement += " and  level='2'";
        }
        // 根据“一级模块列表”的值进行查询
        if (StringUtil.isNotBlank(leveloneselected) && !StringUtil.equals(leveloneselected, "null")) {
            whereStatement += " and  sortType='" + leveloneselected + "'";
        }

        // 根据当前页等条件查询
        List customList = getListWithFanyeHref(request, TABLE, whereStatement
                                                               + BaseDAO.WHERE_DELETE,
            " order by id desc", LIST, fanyeHref);
        if (customList != null && customList.size() > 0) {
            for (Object object : customList) {
                Custom custom = (Custom) object;
                Custom father = (Custom) baseDao.findOneObject("Custom", "customId", custom
                    .getSortType());
                if (father != null) {
                    custom.setSortType(father.getTitle());
                }
                if (StringUtil.isNotBlank(custom.getTitle()))
                    if (custom.getTitle().getBytes().length > length)
                        custom.setTitle(ZhzStringUtil.subStringWithDot(custom.getTitle(), length));
            }

        }

        // 将一级模块的列表放入页面
        request.setAttribute("level_arraylist", getSpecLevelList(1));

        return mapping.findForward("custom-list");
    }

    /**
     * 
     * 添加一级模块
     * 
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     */
    public ActionForward customaddlevelone(ActionMapping mapping, ActionForm form,
                                           HttpServletRequest request, HttpServletResponse response) {

        request.setAttribute("writer", ZhzSecurityUtil.getOperatorName());

        // 列出所有通过审核的顶级模块
        request.setAttribute("level_arraylist", getCustomByLevelAndApproveState(0, 1));

        request.setAttribute("addtionalCustom", map);
        return mapping.findForward("custom-add-levelone");
    }

    /**
     * 
     * 保存添加的一级模块
     * 
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     */
    public ActionForward customsavelevelone(ActionMapping mapping, ActionForm form,
                                            HttpServletRequest request, HttpServletResponse response) {

        // 获取模块的主内容
        String customcontent = ZhzHttpRequestUtil.getParameters(request, "customcontent");
        // 获取标题
        String title = ZhzHttpRequestUtil.getParameters(request, "title");
        // 获取父模块
        String levelselected = ZhzHttpRequestUtil.getParameters(request, "levelselected");
        // 获取排序
        String sortNumber = ZhzHttpRequestUtil.getParameters(request, "sortNumber");
        // 获取是否为链接的标记
        String iflink = ZhzHttpRequestUtil.getParameters(request, "iflink");

        Custom custom = new Custom();

        custom.setTitle(title);
        custom.setContent(customcontent);
        custom.setWriter(ZhzSecurityUtil.getOperatorName());
        custom.setLevel("1");
        custom.setKeyword(null);
        custom.setSortType(levelselected);
        String pubdate = request.getParameter("pubdate");
        if (StringUtil.isNotBlank(pubdate)) {
            custom.setPubDate(ZhzDateUtil.getYYYYMDDDate(request.getParameter("pubdate")));
        } else {
            custom.setPubDate(new Date());
        }
        custom.setHit(0);
        custom.setAproveState(0);
        custom.setAproveTime(null);
        custom.setEditor(ZhzSecurityUtil.getOperatorName());
        custom.setEditorTime(new Date());
        custom.setIfDelete(0);
        if (StringUtil.isNotBlank(sortNumber) && StringUtil.isNumeric(sortNumber)) {
            custom.setSortNumber(Integer.valueOf(sortNumber));
        } else {
            custom.setSortNumber(getMaxSortNumber(levelselected));
        }
        //对链接类型进行特殊处理
        if (StringUtil.isNotBlank(iflink)) {
            custom.setKeyword(LINK);
            custom.setContent(ZhzHttpRequestUtil.getParameters(request, "linkurl"));
        } else {
            custom.setKeyword(CUSTOM);
        }

        baseDao.select("from custom where ");

        boolean x = baseDao.save(custom);

        if (x) {
            request.setAttribute("add", "add");
            request.setAttribute("addresult", x);
        }

        return mapping.findForward("custom-result");
    }

    /**
     * 添加二级模块
     * 
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     */
    public ActionForward customadd(ActionMapping mapping, ActionForm form,
                                   HttpServletRequest request, HttpServletResponse response) {

        request.setAttribute("writer", ZhzSecurityUtil.getOperatorName());
        // 列出所有通过审核的一级模块
        request.setAttribute("level_arraylist", getCustomByLevelAndApproveState(1, 1));

        request.setAttribute("addtionalCustom", map);

        return mapping.findForward("custom-add-leveltwo");

    }

    /**
     * 保存添加的二级模块
     * 
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     */
    public ActionForward customsave(ActionMapping mapping, ActionForm form,
                                    HttpServletRequest request, HttpServletResponse response) {

        // 获取模块的主内容
        String customcontent = ZhzHttpRequestUtil.getParameters(request, "customcontent");
        // 获取标题
        String title = ZhzHttpRequestUtil.getParameters(request, "title");
        // 获取父模块
        String leveloneselected = ZhzHttpRequestUtil.getParameters(request, "leveloneselected");
        // 获取排序
        String sortNumber = ZhzHttpRequestUtil.getParameters(request, "sortNumber");
        // 获取是否为链接的标记
        String iflink = ZhzHttpRequestUtil.getParameters(request, "iflink");

        Custom custom = new Custom();

        custom.setTitle(title);
        custom.setContent(customcontent);
        custom.setWriter(ZhzSecurityUtil.getOperatorName());
        custom.setLevel("2");
        custom.setKeyword(null);
        custom.setSortType(leveloneselected);
        String pubdate = request.getParameter("pubdate");
        if (StringUtil.isNotBlank(pubdate)) {
            custom.setPubDate(ZhzDateUtil.getYYYYMDDDate(request.getParameter("pubdate")));
        } else {
            custom.setPubDate(new Date());
        }
        custom.setHit(0);
        custom.setAproveState(0);
        custom.setAproveTime(null);
        custom.setEditor(ZhzSecurityUtil.getOperatorName());
        custom.setEditorTime(new Date());
        custom.setIfDelete(0);
        if (StringUtil.isNotBlank(sortNumber) && StringUtil.isNumeric(sortNumber)) {
            custom.setSortNumber(Integer.valueOf(sortNumber));
        } else {
            custom.setSortNumber(getMaxSortNumber(leveloneselected));
        }

        //对链接类型进行特殊处理
        if (StringUtil.isNotBlank(iflink)) {
            custom.setKeyword(LINK);
            custom.setContent(ZhzHttpRequestUtil.getParameters(request, "linkurl"));
        } else {
            custom.setKeyword(CUSTOM);
        }
        boolean x = baseDao.save(custom);

        if (x) {
            request.setAttribute("add", "add");
            request.setAttribute("addresult", x);
        }

        return mapping.findForward("custom-result");
    }

    /**
     * 编辑定制模块
     * 
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     */
    public ActionForward customedit(ActionMapping mapping, ActionForm form,
                                    HttpServletRequest request, HttpServletResponse response) {

        // 获取模块id
        String customid = ZhzHttpRequestUtil.getParameters(request, "customid");

        // 获取模块内容
        Custom custom = (Custom) baseDao.findOneObject("Custom", "customId", customid);
        request.setAttribute("custom", custom);

        if (custom.getPubDate() != null) {
            String date = new SimpleDateFormat("yyyy-MM-dd").format(custom.getPubDate());
            request.setAttribute("pubDate", date);
        }
        Custom customFather = (Custom) baseDao.findOneObject("Custom", "customId", custom
            .getSortType());
        if (customFather == null) {
            customFather = new Custom();
            customFather.setEditor(custom.getSortType());
            customFather.setWriter(map.get(custom.getSortType()));
        } else {
            customFather.setEditor(customFather.getCustomId() + "");
            customFather.setWriter(customFather.getTitle());
        }
        // 获取其父模块
        request.setAttribute("customFather", customFather);

        if (StringUtil.equals(custom.getLevel(), "1")) {
            // 列出所有通过审核的顶级模块
            request.setAttribute("level_arraylist", getCustomByLevelAndApproveState(0, 1));
            return mapping.findForward("customedit-levelone-form");

        } else if (StringUtil.equals(custom.getLevel(), "2")) {
            // 列出所有通过审核的一级模块
            request.setAttribute("level_arraylist", getCustomByLevelAndApproveState(1, 1));
            return mapping.findForward("customedit-leveltwo-form");

        }
        return null;
    }

    /**
     * 保存编辑后的一级模块
     * 
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     */
    public ActionForward customleveloneeditsave(ActionMapping mapping, ActionForm form,
                                                HttpServletRequest request,
                                                HttpServletResponse response) {

        String customid = ZhzHttpRequestUtil.getParameters(request, "customid");

        String customcontent = ZhzHttpRequestUtil.getParameters(request, "customcontent");

        String title = ZhzHttpRequestUtil.getParameters(request, "title");

        String levelselected = ZhzHttpRequestUtil.getParameters(request, "levelselected");
        // 获取排序
        String sortNumber = ZhzHttpRequestUtil.getParameters(request, "sortNumber");

        // 获取是否为链接的标记
        String iflink = ZhzHttpRequestUtil.getParameters(request, "iflink");

        Custom custom = (Custom) baseDao.findOneObject("Custom", "customId", customid);

        custom.setTitle(title);
        custom.setContent(customcontent);
        custom.setSortType(levelselected);
        String pubdate = request.getParameter("pubdate");
        if (StringUtil.isNotBlank(pubdate)) {
            custom.setPubDate(ZhzDateUtil.getYYYYMDDDate(request.getParameter("pubdate")));
        } else {
            custom.setPubDate(new Date());
        }
        custom.setEditor(ZhzSecurityUtil.getOperatorName());
        custom.setEditorTime(new Date());
        if (StringUtil.isNotBlank(sortNumber) && StringUtil.isNumeric(sortNumber)) {
            custom.setSortNumber(Integer.valueOf(sortNumber));
        } else {
            custom.setSortNumber(getMaxSortNumber(levelselected));
        }
        //对链接类型进行特殊处理
        if (StringUtil.isNotBlank(iflink)) {
            custom.setKeyword(LINK);
            custom.setContent(ZhzHttpRequestUtil.getParameters(request, "linkurl"));
        } else {
            custom.setKeyword(CUSTOM);
        }

        request.setAttribute("edit", true);

        boolean x = baseDao.update(custom);
        if (x) {
            request.setAttribute("edit", "edit");
            request.setAttribute("editresult", x);
        }

        return mapping.findForward("custom-result");
    }

    /**
     * 
     * 保存编辑后的二级模块
     * 
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     */
    public ActionForward customeditsave(ActionMapping mapping, ActionForm form,
                                        HttpServletRequest request, HttpServletResponse response) {

        String customid = ZhzHttpRequestUtil.getParameters(request, "customid");

        String customcontent = ZhzHttpRequestUtil.getParameters(request, "customcontent");

        String title = ZhzHttpRequestUtil.getParameters(request, "title");

        String levelselected = ZhzHttpRequestUtil.getParameters(request, "levelselected");
        // 获取排序
        String sortNumber = ZhzHttpRequestUtil.getParameters(request, "sortNumber");
        // 获取是否为链接的标记
        String iflink = ZhzHttpRequestUtil.getParameters(request, "iflink");

        Custom custom = (Custom) baseDao.findOneObject("Custom", "customId", customid);

        custom.setTitle(title);
        custom.setContent(customcontent);
        custom.setSortType(levelselected);
        String pubdate = request.getParameter("pubdate");
        if (StringUtil.isNotBlank(pubdate)) {
            custom.setPubDate(ZhzDateUtil.getYYYYMDDDate(request.getParameter("pubdate")));
        } else {
            custom.setPubDate(new Date());
        }
        custom.setEditor(ZhzSecurityUtil.getOperatorName());
        custom.setEditorTime(new Date());
        if (StringUtil.isNotBlank(sortNumber) && StringUtil.isNumeric(sortNumber)) {
            custom.setSortNumber(Integer.valueOf(sortNumber));
        } else {
            custom.setSortNumber(getMaxSortNumber(levelselected));
        }
        //对链接类型进行特殊处理
        if (StringUtil.isNotBlank(iflink)) {
            custom.setKeyword(LINK);
            custom.setContent(ZhzHttpRequestUtil.getParameters(request, "linkurl"));
        } else {
            custom.setKeyword(CUSTOM);
        }
        request.setAttribute("edit", true);

        boolean x = baseDao.update(custom);
        if (x) {
            request.setAttribute("edit", "edit");
            request.setAttribute("editresult", x);
        }

        return mapping.findForward("custom-result");
    }

    /**
     * 删除定制模块，其子模块也被删除
     * 
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    public ActionForward customdel(ActionMapping mapping, ActionForm form,
                                   final HttpServletRequest request, HttpServletResponse response)
                                                                                                  throws Exception {

        // 在一个事务中进行
        String delResult = (String) transactionTemplate.execute(new TransactionCallback() {

            public Object doInTransaction(TransactionStatus status) {

                try {
                    String customidString = ZhzStringUtil.ISOtoUTF8AfterTrimIfNotNull(request
                        .getParameter("customid"));
                    if (ZhzStringUtil.isNotNull(customidString)) {
                        Custom custom = (Custom) baseDao.findOneObject("Custom", "customId",
                            customidString);
                        custom.setIfDelete(1);
                        custom.setEditor(ZhzSecurityUtil.getOperatorName());
                        // 将其子模块也删除
                        List<Custom> customlist = baseDao.select("from Custom t where t.sortType= "
                                                                 + customidString);
                        for (Custom c : customlist) {
                            c.setIfDelete(1);
                            custom.setEditor(ZhzSecurityUtil.getOperatorName());
                            custom.setEditorTime(new Date());
                            baseDao.update(c);
                        }
                        baseDao.update(custom);
                    }
                } catch (Exception e) {
                    status.setRollbackOnly();
                    return null;
                }
                return "del";
            }
        });

        if (delResult != null) {
            request.setAttribute("del", "del");
            request.setAttribute("delResult", delResult);
        }
        return mapping.findForward("custom-result");
    }

    /**
     * 
     * 通过ajax请求，获取模块内容
     * 
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ActionForward customContent(ActionMapping mapping, ActionForm form,
                                       HttpServletRequest request, HttpServletResponse response)
                                                                                                throws Exception {
        String customid = ZhzHttpRequestUtil.getParameters(request, "customid");
        if (ZhzStringUtil.isNotNull(customid)) {
            Custom custom = (Custom) baseDao.findOneObject("Custom", "customId", customid);

            request.setAttribute("custom", custom);
        } else {
            return null;
        }
        return mapping.findForward("custom-content");
    }

    /**
     * 审核定制模块，不影响子模块的审核状态
     * 
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    public ActionForward customApprove(ActionMapping mapping, ActionForm form,
                                       HttpServletRequest request, HttpServletResponse response)
                                                                                                throws Exception {

        // 获取所有的参数
        Enumeration allParameter = request.getParameterNames();

        // 0 未审核 1 通过 2 不通过
        String aproveState = ZhzStringUtil.ISOtoUTF8AfterTrimIfNotNull(request
            .getParameter("approveState"));

        final int apoveStateInt = Integer.parseInt(aproveState);

        // 获取选择的所有待审核的模块
        final Set<String> customIdSet = new HashSet<String>();

        String name = null;
        while (allParameter.hasMoreElements()) {
            name = (String) allParameter.nextElement();
            if (ZhzStringUtil.isNotNull(name) && StringUtil.contains(name, "checkbox")) {
                // 将含有值的checkbox，赋值
                customIdSet.add(request.getParameter(name));
            }
        }

        // 在事务中进行
        boolean approveResult = (Boolean) transactionTemplate.execute(new TransactionCallback() {

            public Object doInTransaction(TransactionStatus status) {

                try {
                    Iterator it = customIdSet.iterator();
                    while (it.hasNext()) {
                        String customId = (String) it.next();
                        Custom custom = (Custom) baseDao.findOneObject("Custom", "customId",
                            customId);
                        custom.setAproveState(apoveStateInt);
                        custom.setAproveTime(new Date());
                        custom.setEditor(ZhzSecurityUtil.getOperatorName());
                        custom.setEditorTime(new Date());
                        baseDao.update(custom);
                    }
                } catch (Exception e) {
                    status.setRollbackOnly();
                    return false;
                }
                return true;
            }

        });

        if (approveResult) {
            request.setAttribute("approveResult", approveResult);
            request.setAttribute("app", "app");
        }
        return mapping.findForward("custom-result");
    }

    /**
     * 得到所有的n级模块
     * 
     * @param level
     *            模块级别
     * @return
     */
    public List<String[]> getSpecLevelList(int level) {

        ArrayList<String[]> result = new ArrayList<String[]>();

        // 将未审核的模块加入
        result.addAll(getCustomByLevelAndApproveState(level, 0));
        // 将已审核的模块加入
        result.addAll(getCustomByLevelAndApproveState(level, 1));
        // 将审核不通过的模块加入
        result.addAll(getCustomByLevelAndApproveState(level, 2));

        return result;
    }

    /**
     * 得到符合某种审核状态的所有的n级模块——
     * 
     * @param level
     *            模块级别
     * @param aproveState
     *            审核的状态
     * @return
     */
    @SuppressWarnings("unchecked")
    public List<String[]> getCustomByLevelAndApproveState(int level, int aproveState) {
        ArrayList<String[]> result = new ArrayList<String[]>();

        List<Custom> list = (List<Custom>) baseDao
            .select("from Custom where ifDelete=0 and level='" + level + "' and aproveState='"
                    + aproveState + "' order by customId ASC");
        String[] tempStrings = null;
        // 遍历Custom表中的元素，存于 ArrayList中
        int i = 0;

        if (list != null && list.size() > 0) {
            for (Iterator<Custom> it = list.iterator(); it.hasNext();) {
                Custom ct = (Custom) it.next();
                tempStrings = new String[2];
                tempStrings[0] = ct.getCustomId().toString();
                tempStrings[1] = ct.getTitle();
                result.add(tempStrings);
                i++;
            }
        }
        return result;
    }

    public void setTransactionTemplate(TransactionTemplate transactionTemplate) {
        this.transactionTemplate = transactionTemplate;
    }

    private Integer getMaxSortNumber(String levelselected) {

        if (!StringUtil.isNumericSpace(levelselected)) {
            return 10;
        }
        String sql = "select max(sortNumber) sortNumber from custom where sortType="
                     + levelselected;
        Session session = baseDao.getHibernateTemplate().getSessionFactory().openSession();
        Integer maxId = (Integer) (session.createSQLQuery(sql).addScalar("sortNumber",
            Hibernate.INTEGER)).uniqueResult();
        // 比最大值步进10
        if (maxId != null) {
            return maxId + 10;
        } else {
            return 10;
        }
    }

}